package nil.ed.simulator.request.ui.jfx.event;

import javafx.application.Platform;
import nil.ed.simulator.request.client.activity.BuiltInAttrs;
import nil.ed.simulator.request.common.QQItem;
import nil.ed.simulator.request.enums.events.EventType;
import nil.ed.simulator.request.event.Event;
import nil.ed.simulator.request.event.bus.EventListener;
import nil.ed.simulator.request.repo.RuntimeRepo;
import nil.ed.simulator.request.ui.jfx.bean.qq.QQRow;
import nil.ed.simulator.request.ui.jfx.controller.TableViewController;
import nil.ed.simulator.request.ui.jfx.controller.TopControlPaneController;
import nil.ed.simulator.request.ui.jfx.manager.ControllerManager;

import java.util.Map;

/**
 * @author lidelin.
 */
public class LoginSuccessOrFailedEventListener implements EventListener {
    @Override
    @SuppressWarnings("unchecked")
    public void onEvent(Event event) {
        Map<String, Object> context = (Map<String, Object>) event.getData();
        QQItem qqItem = (QQItem) context.get(BuiltInAttrs.ENTITY_ATTR);
        TableViewController tableViewController = ControllerManager.getTable();
        TopControlPaneController topControlPaneController = ControllerManager.getTop();

        int count = 0;
        for (Object obj : tableViewController.getDataList()) {
            QQRow qqRow = (QQRow) obj;
            if (qqRow.getQqItem() == qqItem) {
                qqRow.setCookieStatus(event.getEventType() == EventType.LOGIN_SUCCESS ? QQRow.COOKIE_STATUS_SUCCESS : QQRow.COOKIE_STATUS_FAILED);
            }
            if (QQRow.COOKIE_STATUS_SUCCESS .equals(qqRow.getCookieStatus())) {
                count++;
            }
        }
        final int sucCount = count;
        Platform.runLater(() -> {
            topControlPaneController.configProgress(RuntimeRepo.QQ_REPO.getAllUnits().size(), sucCount);
        });
    }

    @Override
    public boolean isSupport(Event event) {
        return event.getEventType() == EventType.LOGIN_SUCCESS || event.getEventType() == EventType.LOGIN_FAILED;
    }
}
